package com.tyl.pool;

import java.util.concurrent.*;

/**
 *  Executors线程池三大方法
 * **/
public class Demo1 {
    public static void main(String[] args) {
        /**
         * 三种拒绝策略
         *   new ThreadPoolExecutor.AbortPolicy() //会报异常util.concurrent.RejectedExecutionException
         *   new ThreadPoolExecutor.CallerRunsPolicy()//不会报异常，通过main函数来执行线程
         *   new ThreadPoolExecutor.DiscardPolicy()//不会报异常，丢掉多余线程
         *   new ThreadPoolExecutor.DiscardOldestPolicy()// 不会报异常，会跟最开始的线程竞争
         * **/
        //怎么定义最大线程池？
        // cpu密集型  获取cpu核数，是多大就填写多大。
        // io密集型   判断程序中十分小号io的线程，大于该线程数即可

         //自定义线程池
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors(),
                2,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(5),
                Executors.defaultThreadFactory(),//默认线程工厂
                new ThreadPoolExecutor.DiscardOldestPolicy());//解决策略
        try {
            for (int i = 1; i <=11; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"this Thread!");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }
}
